package com.kongge.algorithm.demo;

import java.util.LinkedList;
import java.util.List;

/**
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 * 例如：
 * 1  2  3  4
 * 5  6  7  8
 * 9  10 11 12
 * 13 14 15 16
 * 打印：1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
 * 
 * @author gaoshiqi
 *
 */
public class PrintMatrixClockwisely implements IAlgorithm{

	public void execute() {
		int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
		List<Integer> resultList = new LinkedList<Integer>();
		printMatrixClockwisely(arr, 4, 4, resultList);
		System.out.println(resultList.toString());
	}

	private void printMatrixClockwisely(int[][] arr, int col, int row, List<Integer> resultList) {
		if (arr == null || col == 0 || row == 0) {
			return;
		}
		int start = 0;
		while (col > start * 2 && row > start * 2) {
			printMatrixInCircle(arr, col, row, start, resultList);
			start ++;
		}
	}
	
	private void printMatrixInCircle(int[][] arr, int col, int row, int start, List<Integer> resultList) {
		int endX = col - 1 - start;
		int endY = row - 1 - start;
		
		// 从左到右打印一行
		for (int i = start; i <= endX; i++) {
			printNumber(resultList, arr[start][i]);
		}
		
		// 从上到下打印一行
		if (start < endY) {
			for (int i = start + 1; i <= endY; i++) {
				printNumber(resultList, arr[i][endX]);
			}
		}
		
		// 从右到左打印一行
		if (start < endX && start < endY) {
			for (int i = endX - 1; i >= start; i--) {
				printNumber(resultList, arr[endY][i]);
			}
		}
		// 从下到上打印一行
		if (start < endY && start < endY - 1) {
			for (int i = endY - 1; i >= start + 1; i--) {
				printNumber(resultList, arr[i][start]);
			}
		}
	}
	
	private void printNumber(List<Integer> resultList, int number) {
		if (resultList != null) {
			resultList.add(number);
		} else {
			System.out.println(number + " ");
		}
	}
}
